package visiopuce.DAO;

import java.math.BigDecimal;
import java.util.ArrayList;

import org.hibernate.Query;

import visiopuce.HibernateUtil;
import visiopuce.objets.Alteration;
import visiopuce.objets.TypePuce;

public class ProbeDAOImpl extends GenericDAOImpl<Object, BigDecimal> implements ProbeDAO {

	/** Constructeur priv� */
	private ProbeDAOImpl() {
	}

	/** Instance unique non pr�initialis�e */
	private static ProbeDAOImpl INSTANCE = null;

	/** Point d'acc�s pour l'instance unique du singleton */
	public static ProbeDAO getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new ProbeDAOImpl();
		}
		return INSTANCE;
	}

	@Override
	public ArrayList<Object> getProbeByBorne(Alteration alteration, long tailleChr, TypePuce typePuce, int seuil) {
		Long debut = Math.max(0, alteration.getDebutHg19() - seuil);
		Long fin = Math.min(alteration.getFinHg19() + seuil, tailleChr);
		ArrayList<Object> genes = null;
		String sql = null;
		Query query;
		sql = "SELECT g FROM Probechr" + alteration.getChromosome().toLowerCase() + " g WHERE g.id.typePuce = :typePuce AND g.id.debutHg19 IS NOT NULL AND g.id.debutHg19 <= :fin AND g.finHg19 IS NOT NULL AND g.finHg19 >= :debut ORDER BY g.id.debutHg19";
		query = HibernateUtil.getSession().createQuery(sql).setParameter("debut", debut);
		query.setParameter("fin", fin);
		query.setParameter("typePuce", typePuce.getIdTypePuce());
		genes = (ArrayList<Object>) query.list();
		return genes;
	}

	@Override
	public String getProbeByAlteration(String chromosome, long position, int idTypePuce) {
		String nom = "";
		Query query;
		String sql = "SELECT g.id.idProbe FROM Probechr" + chromosome.toLowerCase() + " g WHERE ";
		sql += " g.id.debutHg19 <= :position1 AND  g.finHg19 >= :position2";
		if (idTypePuce == 2) {
			sql += " AND g.id.typePuce in (4,6)";
		} else if (idTypePuce == 1) {
			sql += " AND g.id.typePuce in (1,5)";
		} else {
			sql += " AND g.id.typePuce = " + idTypePuce;
		}
		query = HibernateUtil.getSession().createQuery(sql);
		query.setParameter("position1", position);
		query.setParameter("position2", position);
		ArrayList<String> genes = (ArrayList<String>) query.list();
		if (genes.size() > 0) {
			nom = genes.get(0);
		}
		return nom;
	}
}